import { createRouter, createWebHistory } from 'vue-router'
import { ElMessage } from 'element-plus'
import AdminLayout from '@/layout/AdminLayout.vue'

const Login = () => import('@/views/auth/Login.vue')
const Dashboard = () => import('@/views/dashboard/Dashboard.vue')
const Profile = () => import('@/views/user/Profile.vue')
const UserManage = () => import('@/views/user/UserManage.vue')
const ContentManage = () => import('@/views/content/ContentManage.vue')
const RecommendManage = () => import('@/views/community/RecommendManage.vue')
const CityManage = () => import('@/views/city/CityManage.vue')
const TravelNoteManage = () => import('@/views/travel-note/TravekNoteManage.vue')
const TravelPlanManage = () => import('@/views/travel-plan/TravelPlanManage.vue')

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { title: '登录', requiresAuth: false }
  },
  {
    path: '/',
    component: AdminLayout,
    redirect: '/dashboard',
    meta: { requiresAuth: true },
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: Dashboard,
        meta: { title: '仪表盘', requiresAuth: true }
      },
      {
        path: 'profile',
        name: 'Profile',
        component: Profile,
        meta: { title: '个人中心', requiresAuth: true }
      },
      {
        path: 'users',
        name: 'Users',
        component: UserManage,
        meta: { title: '用户管理', requiresAuth: true }
      },
      {
        path: 'content',
        name: 'Content',
        component: ContentManage,
        meta: { title: '审核管理', requiresAuth: true }
      },
      {
        path: 'city',
        name: 'City',
        component: CityManage,
        meta: { title: '城市管理', requiresAuth: true }
      },
      {
        path: 'travelNote',
        name: 'TravelNote',
        component: TravelNoteManage,
        meta: { title: '游记管理', requiresAuth: true }
      },
      {
        path: 'community',
        name: 'Community',
        component: RecommendManage,
        meta: { title: '推荐设置', requiresAuth: true }
      },
      {
        path: 'travelPlan',
        name: 'TravelPlan',
        component: TravelPlanManage,
        meta: { title: '旅行计划管理', requiresAuth: true }
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 设置页面标题
  document.title = to.meta.title
    ? `${to.meta.title} - Trave后台管理`
    : 'Trave后台管理'

  // 检查是否需要登录
  const token = localStorage.getItem('adminToken')

  if (to.meta.requiresAuth && !token) {
    // 需要登录但未登录，跳转到登录页
    ElMessage.warning('请先登录！')
    next('/login')
  } else if (!to.meta.requiresAuth && token && to.path === '/login') {
    // 已登录用户访问登录页，跳转到首页
    next('/dashboard')
  } else {
    next()
  }
})

export default router

